package com.itheima.reggie.controller;

import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.UserDto;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.exception.CustomException;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.SMSUtils;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * @author Lff
 * @date 2022/3/2
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserService userService;

    /**
     * 验证码发送
     *
     * @param user
     * @param request
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpServletRequest request) {
        //生成验证码
        String code = ValidateCodeUtils.generateValidateCode(6).toString();
        //获取手机号
        String phone = user.getPhone();
        //发送验证码
        log.info("您的验证码是===>{}", code);

//        boolean flag = SMSUtils.sendMessage(phone, code);
        boolean flag = true;
        if (flag) {
            //发送成功！ 存到session域中，key=>phone value => code
           /* request.getSession().setAttribute(phone, code);
            // 验证码有效时间5分钟
            request.getSession().setMaxInactiveInterval(60 * 5);
            return R.success("验证码短信发送成功！");*/
            //验证码存到缓存中 键是电话号码
            //设置验证码的有效时间 5分S钟
            redisTemplate.opsForValue().set(user.getPhone().toString(), code, 5, TimeUnit.MINUTES);
            return R.success("短信验证码发送成功，请留意手机短信！");
//            return R.success(code);
        }
        //发送失败！
        throw new CustomException("验证码发送失败，请重试！");
    }

    @PostMapping("/login")
    public R<User> login(@RequestBody UserDto user, HttpServletRequest request) {
        //获取Session中的验证码
//        String code = request.getSession().getAttribute(user.getPhone()).toString();
        //从缓存里获取密码
        String code = redisTemplate.opsForValue().get(user.getPhone().toString()).toString();
        redisTemplate.delete(user.getPhone().toString());
        if (user.getCode().equals(code)) {
            //验证通过,进行登录或注册
            User login = userService.loginOrRegister(user);
            if (login.getId() == null) {
                return R.error("登陆失败！");
            }
            request.getSession().setAttribute("user", login.getId());
            log.info("login ==> {}", login.toString());
            return R.success(login);
        }
        return R.error("验证码错误,请重新输入！");
    }

    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        request.getSession().removeAttribute("user");
        return R.success("退出成功！");
    }
}
